#!/usr/bin/env python

# -*- coding: utf-8 -*

"""
摄像头 Opencv VideoCapture
"""

import logging

import cv2

from py_code.SingletonType import SingletonType
from py_code.driver.Driver import Driver


class Cap(Driver, metaclass=SingletonType):
    """
    摄像头实例，Opencv的VideoCapture
    """
    cap = None

    def open(self):
        super().open()
        self.cap = cv2.VideoCapture(0)
        logging.debug(f"摄像头打开")

    def close(self, destoryWindows=True):
        """
        关闭摄像头，释放资源
        @param destoryWindows {bool} 是否销毁所有窗口
        """
        self.cap.release()
        logging.debug(f"摄像头关闭")
        if destoryWindows:
            cv2.destoryAllWindows()
        super().close()

    def readOrFail(self):
        """
        
        """
        ret, frame = self.cap.read()
        if not ret:
            raise f"读取视频帧错误"
        return frame
